<?php
/**
 * Created by sublime 3.
 * Auth: Inhere
 * Date: 14-12-12
 * Time: 10:35
 * Uesd: 主要功能是 hi
 */
namespace ulue\parts\session\handler;


class MemcachedSessionHandler extends AbstractSessionHandler
{
    protected $memcached=null;

    /**
     * Property ttl. 存储周期
     * @var  integer
     */
    protected $ttl = null;

    public function __construct(\Memcached $memcached=null, $options=[])
    {
        if (!self::isSupported())
        {
            throw new \DRuntimeException('Memcache Extension is not available');
        }

        $this->memcached = $memcached instanceof \Memcached ? $memcached : new \Memcached();

        $this->ttl = isset($options['expire']) ? $options['expire'] : 2*60*60;

        parent::__construct($options);
    }


    static public function isSupported()
    {
        return (extension_loaded('memcached') && class_exists('Memcached'));
    }

    public function open($path, $name)
    {
        return true;
    }

    public function read( $id )
    {
        return $this->memcached->get($this->prefix.$id) ?: '';
    }

    public function write( $id ,  $data )
    {
        return $this->memcached->set($this->prefix.$id, $data, 0, time() + $this->ttl);
    }

    public function destroy( $id )
    {
        return  $this->memcached->delete($this->prefix.$id);
    }

    public function gc( $maxlifetime )
    {
        return  true;
    }

    public function close()
    {
        return true;
    }

    public function getMemcache()
    {
        return $this->memcached;
    }

    public function setMemcache($mem)
    {
        return $this->memcached = $mem;
    }
}